package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBody;
import com.itheima.pojo.Result;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/emps")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @GetMapping
    public Result findAllByPage(@RequestParam(value = "name",required = false)String name,
                                @RequestParam(value = "gender",required = false)Integer gender,
                                @RequestParam(value = "begin",required = false)String begin,
                                @RequestParam(value = "end",required = false)String end,
                                @RequestParam(value = "page",defaultValue = "1")Integer page,
                                @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        PageBody allByPage = employeeService.findAllByPage(name, gender, begin, end, page, pageSize);
        return Result.success(allByPage);
    }
    @GetMapping("/list")
    public Result findAllByPage(){
        List<Emp> emps  = employeeService.findAll();
        return Result.success(emps);
    }
    @DeleteMapping
    public Result deleteByIds(@RequestParam("ids")String ids){
        // TODO 批量删除
        String[] split = ids.split(",");
        List<Integer> objects = (List<Integer>) CollectionUtils.arrayToList(split);
        employeeService.deleteByIds(objects);
        return Result.success();
    }
    @PostMapping
    public Result saveEmp(@RequestBody Emp emp){
        employeeService.saveEmp(emp);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result findEmpById(@PathVariable("id") Integer id){
        Emp emp = employeeService.findEmpById(id);
        return Result.success(emp);
    }
    @PutMapping
    public Result updateEmpById(@RequestBody Emp emp){
        employeeService.updateEmpById(emp);
        return Result.success();
    }
}
